/*
 * Copyright (C) 2009  Sylvain Maucourt (smaucourt@gmail.com)
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 *
 */
package net.sylvek.where;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;

import java.util.concurrent.Executors;

public class FriendsOverlay extends ItemizedOverlay<OverlayItem> {

    static final int MAX = 500;

    private FriendOverlay[] items = new FriendOverlay[MAX];

    private int size = 0;

    private final Context context;

    private final Builder d;

    private LayoutInflater factory;

    private WebView webpage;

    private AlertDialog profile;

    public FriendsOverlay(Context context)
    {
        super(null);
        this.context = context;

        factory = LayoutInflater.from(context);
        d = new AlertDialog.Builder(context);

        webpage = new WebView(context) {
            @Override
            public boolean onCheckIsTextEditor()
            {
                /**
                 * needed to open softkeyboard
                 */
                return true;
            }

        };
        webpage.getSettings().setJavaScriptEnabled(true);
        webpage.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url)
            {
                view.loadUrl(url);
                return true;
            }
        });
        profile = new AlertDialog.Builder(context).setView(webpage).create();

        /* fix bug: http://www.anddev.org/viewtopic.php?p=26461 */
        this.setLastFocusedIndex(-1);
        populate();
    }

    @Override
    public void draw(Canvas canvas, MapView mapView, boolean shadow)
    {
        /* do not display the shadow */
        super.draw(canvas, mapView, false);
    }

    @Override
    protected OverlayItem createItem(int i)
    {
        final OverlayItem result = items[i];

        final LayerDrawable marker = (LayerDrawable) context.getResources().getDrawable(R.drawable.marker);
        final Drawable photo = WhereUtils.getToCache(context, result.getSnippet());

        if (photo != null) {
            marker.setDrawableByLayerId(R.id.photo, photo);
            marker.setDrawableByLayerId(R.id.frame, context.getResources().getDrawable(R.drawable.frame));
        } else {
            Drawable frame = new ColorDrawable();
            frame.setBounds(0, 0, 0, 0);
            marker.setDrawableByLayerId(R.id.frame, frame);
            Executors.defaultThreadFactory().newThread(new Runnable() {

                @Override
                public void run()
                {
                    final Bitmap bitmap = WhereUtils.getImageBitmap(FbClient.HTTP_GRAPH + result.getSnippet() + "/picture");
                    if (bitmap != null) {
                        boolean success = WhereUtils.storeToCache(context, result.getSnippet(), bitmap);
                        if (success) {
                            final Drawable photo = WhereUtils.getToCache(context, result.getSnippet());
                            marker.setDrawableByLayerId(R.id.photo, photo);
                            marker.setDrawableByLayerId(R.id.frame, context.getResources().getDrawable(R.drawable.frame));
                            result.setMarker(boundCenter(marker));
                        }
                    }
                }

            }).start();
        }

        result.setMarker(boundCenter(marker));

        return result;
    }

    @Override
    public int size()
    {
        return size;
    }

    @Override
    protected boolean onTap(int index)
    {
        super.onTap(index);
        showProfile(index);
        return true;
    }

    public OverlayItem showProfile(int index)
    {
        final OverlayItem item = getItem(index);
        setFocus(item);
        return showProfile(item);
    }

    public OverlayItem showProfile(final OverlayItem item)
    {
        d.setItems(R.array.ask_show, new OnClickListener() {

            public void onClick(DialogInterface dialog, int which)
            {
                switch (which) {
                default:
                    // doesn't work properly :-/
                    // webpage.loadUrl(FbClient.URL_PROFIL + item.getSnippet());
                    // profile.show();
                    context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(FbClient.URL_PROFIL + item.getSnippet())));
                    break;
                }
            }

        });

        View customTitle = factory.inflate(R.layout.custom_title, null);
        TextView name = (TextView) customTitle.findViewById(R.id.name);
        TextView update = (TextView) customTitle.findViewById(R.id.update);

        try {
            long updated = Long.parseLong(((FriendOverlay) item).update);
            CharSequence toDisplay = DateUtils.getRelativeTimeSpanString(updated, System.currentTimeMillis(),
                    DateUtils.MINUTE_IN_MILLIS);
            update.setText(toDisplay);
        } catch (NumberFormatException e) {
            Log.e("date.parse", e.getMessage());
        }

        name.setText(item.getTitle());

        d.setCustomTitle(customTitle);
        d.show();
        return item;
    }

    public void update(FriendOverlay[] items, int size)
    {
        this.items = items;
        this.size = size;

        /* fix bug: http://www.anddev.org/viewtopic.php?p=26461 */
        this.setLastFocusedIndex(-1);
        populate();
    }

    public String[] getNames()
    {
        String[] names = new String[size];
        for (int i = 0; i < size; i++) {
            names[i] = getItem(i).getTitle();
        }
        return names;
    }

    public String[] getNamesAndUpdate()
    {
        String[] names = new String[size];
        for (int i = 0; i < size; i++) {
            FriendOverlay item = (FriendOverlay) getItem(i);
            names[i] = item.getTitle() + "-" + item.update;
        }
        return names;
    }

    public OverlayItem resetPositionFocus()
    {
        if (size > 0) {
            setLastFocusedIndex(0);
            return getItem(0);
        }

        return null;
    }
}
